package com.android.myfilm.activities;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.android.external.api.RottenTomatoesManager;
import com.android.external.api.RottenTomatoesUtils;
import com.android.external.apirottentomatoes.model.Movie;
import com.android.myfilm.R;
import com.android.myfilm.pojo.MovieResultItem;

public class ProgressTask extends AsyncTask<String, Void, Map<String, Bitmap>> {

	private static final String TAG = "ProgressTask";
	
    private ProgressDialog dialog;
    private MoviesList activity;
    private Context context;
    private Set<Movie> movies;
    private RottenTomatoesManager rt;
    private Map<String, Set<String>> directors;
    
    public ProgressTask(MoviesList movieListActivity) {
    	this.directors = new HashMap<String, Set<String>>();
    	this.rt = new RottenTomatoesManager();
        this.activity = movieListActivity;
        this.context = movieListActivity;
        this.dialog = new ProgressDialog(context);
    }

    protected void onPreExecute() {
        this.dialog.setMessage("Loading. Please wait...");
        this.dialog.show();
    }

	protected Map<String, Bitmap> doInBackground(String... params) {
		movies = rt.searchMovies(this.activity.getIntent().getExtras().getString("searchMovieText"), null, null);
		
		List<MovieResultItem> moviesResultList = RottenTomatoesUtils.fromMoviesToMovieResultList(movies);
		
		return loadCache(moviesResultList);
	}
	
	 protected void onPostExecute(Map<String, Bitmap> cache) {
		 
		 this.activity.setListAdapter(
				 new MyCustomArrayAdapter(this.activity, R.layout.custom_row_view, RottenTomatoesUtils.fromMoviesToMovieResultList(movies), cache));
		 ListView lv = activity.getListView();
		 lv.setTextFilterEnabled(true);
		 
		 final Set<Movie> _movies = movies;
		 final MoviesList _activity = activity;
		 
		 lv.setOnItemClickListener(new OnItemClickListener() {
			  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				  
				  View v = (((LinearLayout) view).getChildAt(0));
				  String selection = ((LinearLayout)v).getTag().toString();
				  
				  //fetch directors list for selected movie
				  Movie m = RottenTomatoesUtils.getMovie(_movies, selection);
				  directors.put(Integer.toString(m.getId()), rt.getDirectors(m.getId()));
				  
				  Intent mIntent = new Intent(activity.getApplicationContext(), MovieForm.class);
				  
				  int k = directors.get(Integer.toString(m.getId())).size();
				  mIntent.putExtra("directors", directors.get(Integer.toString(m.getId())).toArray(new String[k]));
				  mIntent.putExtra("movie", m);
				  
				  _activity.startActivity(mIntent);
//				  _activity.finish();
			  }
		  });
		 
		 if (dialog.isShowing()) {
			 dialog.dismiss();
	     }
     }
	 
	 private Map<String, Bitmap> loadCache(List<MovieResultItem> moviesResultList) {
		 Map<String, Bitmap> cache = new HashMap<String, Bitmap>();
			Bitmap b;
			for (MovieResultItem mr : moviesResultList) {
				try {
					String posterURL = mr.getPoster();
					b = BitmapFactory.decodeStream(new URL(posterURL).openStream());
					if (posterURL != null && posterURL.contains("default"))  {
						Bitmap b_scaled = Bitmap.createScaledBitmap(b, 61, 91, false);
						cache.put(mr.getPoster(), b_scaled);
					}
					else 
						cache.put(mr.getPoster(), b);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return cache;
	 }
}